// pages/present/lindex.js
const md5 = require("../../utils/md5")
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js')
import axios from "../network/index"
// import areaList from '../../utils/area.js'
import {
  fileUrl
} from "../network/index"
let timer
let timer2
let app = getApp()
var scrollNum;
var currentScroll;
var loading = false;
var projectLoading = false;
var projectLoading2 = false;
var qqmapsdk;
var typeCode;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    nameTypeList: ['装修', '空调', '采暖', '净水', '新风', '弱电'],
    nameType: '',
    showCity: false,
    // areaList: {},
    userId: "",
    materials: [],
    cityCode: '',
    cityName: "",
    defaultIndex: "",
    materialsCopy: [],
    modal: false, //上传图片弹出
    filetype: "1", //上传文件的类型 是发票，还是材料
    unfold: false,
    unfold2: false,
    province: '',
    city: '',
    latitude: '',
    longitude: '',
    currentMaterials: "",
    projectData: "",
    projectData2: "",
    seletctMaterialsStatus: false,
    currentV: {},
    currentV2: {},
    number: 0,
    memo: '', //备注
    totalPrice: 0,
    taskNumber: [{
      number: 1,
      selectMaterialsLable: "",
      selectMaterialsValue: "",
      price: '',
      unitPrice: '',
      image: [],
      seletctMaterialsStatus: false,
      currentIndex: 0
    }],
    billPicture: [],
    inventoryPicture: [],
    showList: false,
    submitLoading: false,
    showLists: false,
    showDetail: false,
    detailInfo: {},
    spaceText: "数据加载中...",
    orderNoList: [{
      label: "票据单号",
      value: ""
    }],
    title: "",
    cityList: [],
    id: "",
    UpOrDown: false,
  },
  nameTypeChange(e) {
    this.setData({
      nameType: e.detail.value,
      UpOrDown: false
    })
    this.saveCache()
  },
  catchNameType() {
    this.setData({
      UpOrDown: true
    })
  },
  cancelSelectNameType() {
    this.setData({
      UpOrDown: false
    })
  },
  addOderNo() {
    let list = this.data.orderNoList
    list.push({
      label: "票据单号",
      value: ""
    })
    this.setData({
      orderNoList: list
    })
    this.saveCache()
  },
  delOrderNo(e) {
    let index = e.currentTarget.dataset.index
    let list = this.data.orderNoList
    list.splice(index, 1)
    this.setData({
      orderNoList: list
    })
    this.saveCache()
  },
  orderNoIpt(e) {
    let index = e.currentTarget.dataset.index
    let list = this.data.orderNoList
    list[index].value = e.detail.value
    this.setData({
      orderNoList: list
    })
    this.saveCache()
  },
  cancel() {
    this.setData({
      modal: false,
    })
  },
  move() {},
  //预览
  prePicture() {
    wx.previewImage({
      current: this.data.detailInfo.img,
      urls: [this.data.detailInfo.img]
    })
  },
  //打开详情弹窗
  openDetail(e) {
    let data = e.currentTarget.dataset.data
    this.setData({
      showDetail: true,
      detailInfo: data
    })
  },

  //关闭详情弹窗
  closeDetail() {
    this.setData({
      showDetail: false,
    })
  },
  //打开城市选择弹窗
  openCity() {
    this.setData({
      showCity: true
    })
  },
  //关闭城市选择弹窗
  closeCity() {
    this.setData({
      showCity: false,
    })
  },
  //打开上拉列表
  showListSwtich() {
    this.setData({
      showList: !this.data.showList
    })
    if (this.data.showList) {
      setTimeout(() => {
        this.setData({
          showLists: true
        })
      }, 220);
    } else {
      setTimeout(() => {
        this.setData({
          showLists: false
        })
        currentScroll = scrollNum
        wx.pageScrollTo({
          scrollTop: currentScroll,
          duration: 0
        })
      }, 30);
    }
  },
  numChange(e) {
    let index = e.currentTarget.dataset.index
    let taskNumber = this.data.taskNumber
    let defaultPrice = taskNumber[index].unitPrice
    let count = taskNumber[index].number
    this.setData({
      [`taskNumber[${index}].number`]: e.detail,
      [`taskNumber[${index}].price`]: count * defaultPrice,
    })
    this.sumPrice()
  },
  //上传文件
  modal(e) {
    let type = e.currentTarget.dataset.type
    this.setData({
      modal: true,
      type
    })
  },
  //保存缓存
  saveCache() {
    let data = this.data
    wx.setStorageSync('saveCache' + typeCode, data)
  },

  //计算总金额
  sumPrice() {
    let totalPrice = 0
    let taskNumber = this.data.taskNumber
    taskNumber.forEach(v => {
      if (v.price == '') {} else {
        totalPrice += parseFloat(v.price)
      }
    })

    this.setData({
      totalPrice
    })
    this.saveCache()
  },
  //获取单价的值
  price(e) {
    let dataset = e.currentTarget.dataset
    let index = dataset.index
    //  let value = this.validateNumber(e.detail.value)
    let value = e.detail.value
    let taskNumber = this.data.taskNumber
    this.setData({
      [`taskNumber[${index}].unitPrice`]: value,
      [`taskNumber[${index}].price`]: (value * taskNumber[index].number).toFixed(2)
    })
    this.sumPrice()
  },

  closeSelect(e) {
    let index = e.currentTarget.dataset.index
    let taskNumber = this.data.taskNumber
    this.setData({
      [`taskNumber[${index}].seletctMaterialsStatus`]: false
    })
    this.saveCache()
  },

  validateNumber(e) {
    return e.replace(/[\D\.]/g, '')
  },

  //备注
  memoIpt(e) {
    this.setData({
      memo: e.detail.value
    })
    this.saveCache()
  },
  //点击科目选择下拉框
  confirmMaterials(e) {
    let index = e.currentTarget.dataset.index
    let taskNumber = this.data.taskNumber
    if (!taskNumber[index].seletctMaterialsStatus) {
      taskNumber.forEach(item => {
        item.seletctMaterialsStatus = false
      })
      taskNumber[index].seletctMaterialsStatus = true
      this.setData({
        taskNumber,
        materials: this.data.materialsCopy
      })
    } else {
      this.setData({
        [`taskNumber[${index}].seletctMaterialsStatus`]: !taskNumber[index].seletctMaterialsStatus,
      })
    }
    this.saveCache()
  },

  openSelectList(e) {
    loading = false
    // let index = e.currentTarget.dataset.index
    let taskNumber = this.data.taskNumber
    taskNumber.forEach(item => {
      item.seletctMaterialsStatus = false
    })
    // taskNumber[index].seletctMaterialsStatus = true
    this.setData({
      taskNumber,
      materials: this.data.materialsCopy
    })
  },
  confirmSelect() {
    projectLoading = false
    this.setData({
      unfold: !this.data.unfold
    })
    this.saveCache()
  },
  confirmSelect2() {
    projectLoading2 = false
    this.setData({
      unfold2: !this.data.unfold2
    })
    this.saveCache()
  },
  //数量加减
  handelNumberAdd(e) {
    let index = e.currentTarget.dataset.index
    let taskNumber = this.data.taskNumber
    if (taskNumber[index].selectMaterialsValue == '') {
      wx.showToast({
        title: '请正确选择报销材料',
        icon: "none"
      })
      return
    }
    taskNumber[index].number++
    let defaultPrice = taskNumber[index].unitPrice
    let count = taskNumber[index].number

    this.setData({
      [`taskNumber[${index}].number`]: count,
      [`taskNumber[${index}].price`]: (count * defaultPrice).toFixed(2),
      [`taskNumber[${index}].seletctMaterialsStatus`]: false,
    })
    this.sumPrice()
  },
  //数量加减
  handelNumberMinus(e) {
    let dataset = e.currentTarget.dataset
    let index = dataset.index
    let taskNumber = this.data.taskNumber
    let defaultPrice = taskNumber[index].unitPrice
    if (taskNumber[index].selectMaterialsValue == '') {
      wx.showToast({
        title: '请先选择报销材料',
        icon: "none"
      })
      return
    }
    if (taskNumber[index].number < 2) {
      return
    } else {
      taskNumber[index].number--
    }
    let count = taskNumber[index].number
    this.setData({
      [`taskNumber[${index}].number`]: count,
      [`taskNumber[${index}].price`]: (count * defaultPrice).toFixed(2),
      [`taskNumber[${index}].seletctMaterialsStatus`]: false,
    })
    this.sumPrice()
  },
  //数量加减结束
  // 添加任务
  addTask() {
    let taskNumber = this.data.taskNumber
    taskNumber.push({
      number: 1,
      price: '',
      unitPrice: '',
      selectMaterialsLable: '',
      selectMaterialsValue: '',
      firstchoice: false,
      seletctMaterialsStatus: false
    })

    this.setData({
      taskNumber
    })
    this.saveCache()
  },
  //输入数量
  numberClick(e) {
    let currentTaskIndex = e.currentTarget.dataset.index
    let taskNumber = this.data.taskNumber
    let number = e.detail.value
    let currentPrice = number * taskNumber[currentTaskIndex].unitPrice
    taskNumber[currentTaskIndex].price = currentPrice.toFixed(2)
    taskNumber[currentTaskIndex].number = number
    this.sumPrice()

    this.setData({
      taskNumber,
    })
    this.saveCache()
  },
  getProject(val) {
    // var url = this.data.id == 3 ? '/supplierBackCard' : '/api/reimbursed/getProjecAllData'
    var url = '/api/reimbursed/getProjecAllData'
    axios({
      url,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        userId: wx.getStorageSync('userId'),
        searchVal: val,
      }
    }).then(v => {
      this.setData({
        // projectData: this.data.id == 3 ? v.data.content : v.data
        projectData: v.data
      })
      if (!v.data || !v.data.length) {
        this.data.currentV = {}
      }
    })
  },
  getProject2(val) {
    var url = '/supplierBackCard'
    axios({
      url,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        userId: wx.getStorageSync('userId'),
        searchVal: val,
      }
    }).then(v => {
      this.setData({
        projectData2: v.data.content
      })
      if (!v.data.content || !v.data.content.length) {
        this.data.currentV2 = {}

      }
    })
  },
  //获取材料
  getMaterials(v) {
    this.setData({
      spaceText: "数据加载中..."
    })

    axios({
      url: "/api/reimbursed/getMaterialAllData",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      method: "POST",
      data: {
        searchVal: v,
        type: typeCode
      }
    }).then(v => {
      this.setData({
        materials: v.data,
        materialsCopy: JSON.parse(JSON.stringify(v.data)),
        spaceText: v.data && v.data.length > 0 ? '' : '暂无数据'
      })
    }).catch(V => {
      wx.showToast({
        title: V,
        icon: "none"
      })
    })
  },
  //项目下拉获取选中  的值
  currentValue(e) {
    projectLoading = true
    this.setData({
      currentV: e.currentTarget.dataset,
      unfold: false,
    })
    this.saveCache()
  },
  currentValue2(e) {
    projectLoading2 = true
    this.setData({
      currentV2: e.currentTarget.dataset,
      unfold2: false,
    })
    this.saveCache()
  },

  //删除该任务
  delTask(e) {
    let _this = this
    let currentDelTask = e.currentTarget.dataset.index
    let taskNumber = this.data.taskNumber
    wx.showModal({
      title: '提示',
      content: "是否删除该任务",
      success(res) {
        if (res.confirm) {
          wx.showToast({
            title: '删除成功',
          })

          let newtaskNumber = taskNumber.filter((item, index) => currentDelTask != index)
          _this.setData({
            taskNumber: newtaskNumber
          })
          _this.sumPrice()
        } else {
          wx.showToast({
            title: '取消删除',
            icon: "none",
          })
        }
      }
    })

    // }
  },

  //项目搜索的值
  searchProject(e) {
    if (projectLoading) return
    let v = e.detail.value
    clearTimeout(timer)
    timer = setTimeout(() => {
      this.getProject(v)
      this.setData({
        unfold: true
      })
    }, 10)
  },
  searchProject2(e) {
    if (projectLoading2) return
    let v = e.detail.value
    clearTimeout(timer2)
    timer2 = setTimeout(() => {
      this.getProject2(v)
      this.setData({
        unfold2: true
      })
    }, 10)
  },
  //搜素材料
  searchMaterials(e) {
    if (loading) return
    let v = e.detail.value

    let i = e.currentTarget.dataset.index
    let taskNumber = this.data.taskNumber
    let materialsCopy = this.data.materialsCopy
    if (!v) {
      this.setData({
        materials: list,
        [`taskNumber[${i}].seletctMaterialsStatus`]: false,
      })
      return
    }
    let list = materialsCopy.filter(item => item.materialName.indexOf(v) > -1)
    clearTimeout(timer)
    timer = setTimeout(() => {
      this.setData({
        materials: list,
        spaceText: list && list.length > 0 ? '' : '暂无数据'
      })
      if (!taskNumber[i].seletctMaterialsStatus) {
        this.setData({
          [`taskNumber[${i}].seletctMaterialsStatus`]: true,
        })
      }

    }, 20);
  },
  //选择科目
  currentMaterialsV(e) {
    loading = true
    let taskNumber = this.data.taskNumber
    let data = e.currentTarget.dataset.data
    let index = e.currentTarget.dataset.fatherindex
    let val = (data.materialDefaultAmout || data.materialDefaultAmout === 0) ? data.materialDefaultAmout : 0
    taskNumber[index].selectMaterialsLable = data.materialName
    taskNumber[index].selectMaterialsValue = data.materialCode
    taskNumber[index].price = val.toFixed(2)
    taskNumber[index].number = 1
    taskNumber[index].unit = data.unit
    taskNumber[index].unitPrice = val.toFixed(2)
    taskNumber[index].img = data.img
    taskNumber[index].brand = data.brand
    taskNumber[index].stockNum = data.stockNum
    this.setData({
      [`taskNumber[${index}]`]: taskNumber[index],
      [`taskNumber[${index}].seletctMaterialsStatus`]: false
    })
    this.sumPrice()
  },
  //删除图
  delPicture(e) {
    //获取图片的下标
    let {
      index,
      type
    } = e.currentTarget.dataset
    let _this = this
    wx.showModal({
      title: "提示",
      content: "是否删除图片",
      success(res) {
        if (res.confirm) {
          if (type == "1") {
            let billPicture = _this.data.billPicture.filter((item, i) => {
              return !(index == i)
            })

            _this.setData({
              billPicture
            })


          } else {
            let inventoryPicture = _this.data.inventoryPicture.filter((item, i) => {
              return !(index == i)
            })
            _this.setData({
              inventoryPicture
            })
          }
          wx.showToast({
            title: '删除成功',
          })
          _this.saveCache()
        } else if (res.cancel) {
          wx.showToast({
            title: '取消删除',
            icon: "none",
          })
        }
      }
    })
  },
  //上传文件
  uploadFile() {
    this.setData({
      modal: false
    })
    let type = this.data.type
    let _this = this
    let billPicture = this.data.billPicture
    let inventoryPicture = this.data.inventoryPicture

    wx.chooseMessageFile({
      type: "file",
      count: 10,
      extension: app.globalData.extension,
      success: (v) => {
        wx.showLoading({
          title: '文件上传中...',
          mask: true
        })
        v.tempFiles.forEach(item => {
          let suffixArray = item.name.split('.')
          let suffix = suffixArray[suffixArray.length - 1]

          wx.uploadFile({
            filePath: item.path,
            name: 'img',
            url: fileUrl,
            success: (v) => {
              wx.hideLoading({
                success: (res) => {},
              })
              if (v.statusCode != 200) {
                wx.showToast({
                  title: '文件上传失败！',
                  icon: "none",
                })
                return
              }
              let file = JSON.parse(v.data).data
              if (type == "1") {
                inventoryPicture.push({
                  url: file,
                  type: 1,
                  fileType: suffix
                })

              } else {
                billPicture.push({
                  url: file,
                  type: 2,
                  fileType: suffix
                })
              }
              _this.setData({
                billPicture,
                inventoryPicture
              })

            }
          })
        })
      }
    })
    this.saveCache()
  },
  //上传图片
  pricture(e) {
    this.setData({
      modal: false
    })

    let type = this.data.type
    let _this = this
    let billPicture = this.data.billPicture
    let inventoryPicture = this.data.inventoryPicture
    //保存本地预览图

    wx.chooseImage({
      count: 10,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],

      complete(e) {

      },
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFiles
        //获取文件大小
        let ratio = 80
        tempFilePaths.forEach(element => {
          if (element.size > 20971520) {
            wx.showToast({
              title: '图片限制为20M',
              icon: "none",
            })
            return
          } else if (element.size > 10485760)
            ratio = 10
          else if (element.size > 5242880 && element.size < 10485760) {
            ratio = 20
          }
          //压缩图片，只能在真机上使用，模拟器不支持

          wx.compressImage({
            src: element.path,
            quality: ratio,
            success: function (res) {
              wx.showLoading({
                title: '图片上传中...',
                mask: true
              })
              wx.uploadFile({
                filePath: res.tempFilePath,
                name: 'img',
                url: fileUrl,
                success: function (v) {
                  wx.hideLoading({
                    success: (res) => {},
                  })

                  if (v.statusCode != 200) {
                    wx.showToast({
                      icon: "none",
                      title: '图片上传失败',
                    })
                    return
                  }
                  let imageUrl = JSON.parse(v.data).data

                  // taskNumber[index].image.push(imageUrl)

                  // _this.setData({
                  //   taskNumber
                  // })
                  if (type == "1") {
                    inventoryPicture.push({
                      url: imageUrl,
                      type: 1,
                      fileType: 'image'
                    })

                  } else {
                    billPicture.push({
                      url: imageUrl,
                      type: 2,
                      fileType: 'image'
                    })

                  }

                  _this.setData({
                    billPicture,
                    inventoryPicture
                  })
                  _this.saveCache()
                },
                fail: function () {
                  wx.showToast({
                    title: '图片上传失败',
                    icon: "none",
                  })
                }
              })
            },
            fail: function (v) {
              wx.showToast({
                title: '图片压缩失败',
                icon: "none",
              })
            }
          })
        })
      },
      fail: function (v) {
        wx.showToast({
          title: '打开相机失败',
          icon: "none",
        })
      }
    })
  },
  preview(e) {
    // 预览图片
    //该任务的下标

    let type = e.currentTarget.dataset.type
    let previewUrl = e.currentTarget.dataset.image.url
    let file = e.currentTarget.dataset.image.fileType
    if (file != 'image') {
      wx.showLoading({
        title: '正在打开文件',
      })
      wx.downloadFile({
        url: previewUrl,
        success: (res) => {
          const filePath = res.tempFilePath
          wx.openDocument({
            filePath: filePath,
            success: function (res) {
              wx.hideLoading({
                success: (res) => {},
              })
            },
            fail: function (v) {
              wx.showToast({
                title: '打开文件失败，请重试 ',
                icon: "none",
              })
            }
          })
        }
      })
    } else {
      let urls = this.data.inventoryPicture
      if (type == 1) {
        urls = this.data.billPicture
      }

      let urlsDate = urls.map(v => {
        return v.url
      })
      wx.previewImage({
        current: previewUrl,
        urls: urlsDate
      })
    }
  },
  //提交报销
  submitTask() {

    let data = {
      UpOrDown: false,
      nameTypeList: ['装修', '空调', '采暖', '净水', '新风', '弱电'],
      nameType: "",
      modal: false, //上传图片弹出
      filetype: "1", //上传文件的类型 是发票，还是材料
      unfold: false,
      unfold2: false,
      userId: "",
      materials: [],
      materialsCopy: [],
      projectData: "",
      projectData2: "",
      currentMaterials: "",
      seletctMaterialsStatus: false,
      currentV: {},
      currentV2: {},
      number: 0,
      memo: '', //备注
      totalPrice: 0,
      cityCode: '',
      cityName: '',
      taskNumber: [{
        number: 1,
        selectMaterialsLable: "",
        selectMaterialsValue: "",
        price: 0,
        unitPrice: 0,
        image: [],
        seletctMaterialsStatus: false,
        currentIndex: 0
      }],
      billPicture: [],
      inventoryPicture: []
    }
    let taskNumber = this.data.taskNumber
    var flag = true
    var showCheckProjectIdList = ['3', '9', '10', '11', '12', '13', '14', '15'] //需要检测项目是否填写的ID列表
    if (showCheckProjectIdList.includes(this.data.id)) {
      if (Object.keys(this.data.currentV).length == 0) {
        wx.showToast({
          title: '请选择有效的项目',
          icon: "none",
        })
        return
      }
    }
    var showCheckMoneyIdList = ['3', '9', '11', '12', '13', '14', '15'] //需要检测收款账户是否填写的ID列表
    if (showCheckMoneyIdList.includes(this.data.id)) {
      if (Object.keys(this.data.currentV2).length == 0) {
        var str = "请选择有效的收款账户"
        wx.showToast({
          title: str,
          icon: "none",
        })
        return
      }
    }

    var showCheckTypeIdList = ['9', '11', '12'] //需要检测类别是否填写的ID列表
    if (showCheckTypeIdList.includes(this.data.id))
      if (!this.data.nameType) {
        wx.showToast({
          title: "请选择类别",
          icon: "none",
        })
        return
      }

    if (taskNumber && taskNumber.length > 0) {
      taskNumber.forEach(item => {
        if (!item.selectMaterialsValue) flag = false
      })
    }
    if (!flag) {
      wx.showToast({
        title: `检测到不正确的${this.data.title}选择！请检查！`,
        icon: "none",
        duration: 1500
      })
      return
    }
    this.setData({
      submitLoading: true
    })
    let materialData = taskNumber.map(v => {
      return {
        materialAmout: v.price,
        materialCode: v.selectMaterialsValue,
        materialNum: v.number
      }
    })
    let _this = this
    let a = this.data.orderNoList.map(item => item.value)
    let orderNos = []
    if (a && a.length > 0) orderNos = a.filter(item => item)
    if (this.data.id == 3) {
      var datas = {
        imgData: [...this.data.billPicture, ...this.data.inventoryPicture],
        materialData,
        backCardName: this.data.currentV2.v,
        backCardNumber: this.data.currentV2.key,
        supplierName: this.data.currentV2.name,
        projectCode: this.data.currentV.key,
        userId: this.data.userId,
        cityCode: this.data.cityCode,
        cityName: this.data.cityName,
        memo: this.data.memo,
        type: typeCode,
        orderNos
      }
    } else {
      var datas = {
        imgData: [...this.data.billPicture, ...this.data.inventoryPicture],
        materialData,
        projectCode: this.data.currentV.key,
        userId: this.data.userId,
        cityCode: this.data.cityCode,
        cityName: this.data.cityName,
        memo: this.data.memo,
        type: typeCode,
        orderNos,

      }
    }
    if (this.data.id == 9 || this.data.id == 11 || this.data.id == 12 || this.data.id == 13 || this.data.id == 14 || this.data.id == 15) {
      datas['sourceName'] = this.data.nameTypeList[this.data.nameType]
      datas['backCardName'] = this.data.currentV2.v
      datas['backCardNumber'] = this.data.currentV2.key
      datas['supplierName'] = this.data.currentV2.name
    }
    axios({
      url: "/api/reimbursed/submit",
      method: 'POST',
      data: datas
    }, 'application/json').then(v => {
      _this.setData({
        submitLoading: false
      })
      if (v.code == 200) {
        wx.showToast({
            title: "费用报销提交成功",
          }),
          _this.setData({
            ...data
          })
        wx.reLaunch({
          url: '/pages/detail/lindex',
        })
        wx.removeStorageSync('saveCache')
      } else {
        wx.showToast({
          icon: "none",
          title: v.error || v.msg,
        })
      }
    }).catch(v => {
      wx.showToast({
        title: v,
      })
      _this.setData({
        submitLoading: false
      })
    })
  },
  onLoad: function (options) {
    this.setData({
      id: options.id,
    })
    if (options.sbjcode) {
      this.getCityList(options.sbjcode)
    }
    if (options.type) typeCode = options.type
    this.getMaterials('')
    this.getProject('')
    if (this.data.id == 3 || this.data.id == 9 || this.data.id == 11 || this.data.id == 12 || this.data.id == 13 || this.data.id == 14 || this.data.id == 15) {
      this.getProject2('')
    }
    this.getLocations()
    // this.setData({
    //   areaList
    // })
    if (options.jumpName) {
      wx.setNavigationBarTitle({
        title: options.jumpName,
      })
    }
    if (options.title) {
      this.setData({
        title: options.title,
      })
    }


    scrollNum = 0
    currentScroll = 0
    let saveCache = wx.getStorageSync('saveCache' + typeCode)
    //使用md5验证数据是否一样
    let cache = md5.hexMD5(JSON.stringify(saveCache))
    let beforeDate = md5.hexMD5(JSON.stringify(this.data))
    let _this = this
    if (saveCache != '') {
      if (cache != beforeDate) {
        wx.showModal({
          title: "提示",
          content: "检测到上次有未提交的数据，是否恢复！",
          success(res) {
            if (res.confirm) {
              if (saveCache.taskNumber && saveCache.taskNumber.length > 0) {
                saveCache.taskNumber.forEach(item => {
                  item.seletctMaterialsStatus = false
                })
              }
              _this.setData({
                ...saveCache
              })
            } else {

            }
            wx.removeStorageSync('saveCache')
          }
        })
      }
    }
  },
  getCityList(subjectCode) {
    axios({
      url: "/subject/subjectNextSubjectList",
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        subjectCode
      }
    }).then(res => {
      this.setData({
        cityList: res.data.content
      })
    })
  },
  onShow: function () {
    let userId = wx.getStorageSync('userId')

    if (userId) {

      this.setData({
        userId
      })
    } else {
      wx.reLaunch({
        url: '/pages/login/index'
      })
    }


  },
  onPageScroll(e) {
    if (e.scrollTop != 0) {
      scrollNum = e.scrollTop
    }
  },

  getLocations() {
    qqmapsdk = new QQMapWX({
      key: '2SNBZ-NXDK6-RN2S4-EK5GY-WZP6H-AGB2U'
    });
    let vm = this
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();
        } else {
          //调用wx.getLocation的API
          vm.getLocation();
        }
      }
    })
  },
  getLocation: function () {
    let vm = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        vm.getLocal(latitude, longitude)
      },
      fail: function (res) {}
    })
  },
  // 获取当前地理位置
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude,
        longitude
      },
      success: function (res) {

        let {
          province,
          city,
          // city_code,
          // nation_code,
        } = res.result.ad_info
        // let cityCode = city_code.replace(nation_code, '')
        let result = vm.data.cityList.find(item => item.subjectName === city)
        vm.setData({
          province,
          cityName: city,
          latitude,
          longitude,
          cityCode: result ? result.subjectCode : ''
        })

      },
      fail: function (res) {},
      complete: function (res) {}
    });
  },
  confirmCity(e) {
    let val = e.detail.value
    this.setData({
      cityCode: val.subjectCode,
      cityName: val.subjectName,
      showCity: false
    })
    this.saveCache()
  },

})